var MessageBox = wpf.System.Windows.MessageBox;
var File = wpf.System.IO.File;


/** 主方法
 * 
 * 
 * 唯一对外暴露的方法，转换成C#的Task执行
 */
(async function () {
    try {
        var input = local.Input

        // var jsonMap = convertFile(input)
        // var json = mapToJSON(jsonMap)

        // var json = convert(input)
        // local.Output = json

        var lines = input.split('\n')
        writeToFile(input + "\n\n", "F:\\项目\\SafetyStaticTest-Multi\\SafetyStaticTest\\bin\\x86\\Debug\\language\\_temp.txt")
        local.Output = `写入 ${lines.length} 行`
        local.Input = ""

    } catch (error) {
        MessageBox.Show(error.toString());
    }
})()

/** 转换json字符串
 * 
 * @param {String} input 
 * @returns 
 */
function convert(input) {
    var lines = input.split('\n')

    var jsonList = new Map()
    lines.forEach(l => {
        var line = l.trim()

        if (line === "" || line === null)
            return

        if (line.startsWith("//"))
            return

        var value = line.match(/".*"/)
        if (value === "" || value === null)
            return

        var str = trimSE(value, '"')

        jsonList.set(str, str)
    })

    var json = mapToJSON(jsonList)
    json = trimSE(json, '{')
    json = trimSE(json, '}')

    return json
}

function writeToFile(content, path) {
    File.AppendAllText(path, content)
}

/**
 * 
 * @param {String} value 字符串
 * @param {String} char 需要忽略的字符
 * @returns 
 */
function trimSE(value, char) {
    var regex = new RegExp(`^[${char}]+|[${char}]+$`, 'g')
    var str = value.toString().replace(regex, '')
    return str
}

function mapToJSON(map) {
    var obj = Object.fromEntries(map)
    var json = JSON.stringify(obj)
    return json
}


function convertFile(path) {
    var content = File.ReadAllText(path)   // 读取文件所有行
    var lines = content.split('\n')

    MessageBox.Show(lines[0])

    var map = new Map()
    var isRead = false

    lines.forEach(l => {
        var line = l.trim()

        if (line.includes("void LoadLanguage()"))
            isRead = true

        if (line === "}")
            isRead = false

        if (!isRead)
            return

        if (line === "")
            return

        if (line.startsWith("//"))
            return

        var value = line.match(/".*"/).ToString()
        var str = trimSE(value, '"')

        map.set(str, str)
    })

    return map
}
